<!--
描述：table上方查询组件的二次封装
开发人：sunlf
开发日期：2017年8月17日

2017年8月31日
-->

<template lang="pug">
  div.kalix-search
    div.kalix-search-hd
      i.iconfont.icon-query
      | {{title}}
    div.kalix-search-bd
      el-form.search-container(ref="searchForm" v-bind:model="form" v-bind:inline="true" v-on:submit.native.prevent="")
        slot(name="searchFormSlot")
          template(v-for="item in searchFields")
            template(v-if="item.req")
              el-form-item(v-bind:label="item.label" v-bind:prop="item.prop" v-bind:key="item.prop" v-bind:rules="rules.req")
                el-select(v-if="item.type==='select'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType"
                v-bind:clearable="item.clearable")
                  el-option(v-for="option in item.options" v-bind:key="option.value" v-bind:label="option.label" v-bind:value="option.value")
                kalix-select2(v-else-if="item.type==='select2'" v-model="form[item.prop]" v-bind:optionsUrl="item.optionsUrl" v-bind:optionKey="item.optionValue" v-bind:label="item.optionLabel"
                v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType")
                el-input-number(v-else-if="item.type==='number'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType")
                kalix-tree2.inline(v-else-if="item.type==='tree'" v-model="form[item.prop]" v-bind:treeDataURL="item.treeDataURL" v-bind:isAll="item.isAll")
                kalix-object-select2(v-else-if="item.type==='object2'" v-model="form[item.prop]" v-bind:objectsUrl="item.objectsUrl" v-bind:label="item.fieldName")
                kalix-date-picker(v-else-if="item.type==='date'" v-model="form[item.prop]")
                kalix-date-picker(v-else-if="item.type==='year'" v-model="form[item.prop]" type="year")
                kalix-datetime-picker(v-else-if="item.type==='datetime'" v-model="form[item.prop]")
                kalix-dict-select(v-else-if="item.type==='dict'" v-bind:appName="item.appName" v-bind:dictType="item.dictType" v-model="form[item.prop]")
                Kalix-map-select(v-else-if="item.type==='map'" v-bind:appName="item.appName" v-bind:prop="item.prop" v-bind:selectUrl="item.selectUrl" v-model="form[item.prop]"
                v-bind:selectedOptions="item.options" v-on:getProp="getProp" v-on:input="getSelectValue" v-bind:stopChange="item.stopChange")
                input(v-else-if="item.type==='inputHidden'" v-model="form[item.prop]" type="hidden")
                el-input(v-else v-model="form[item.prop]")
            template(v-else)
              <!--span(style="font-size:12px;line-height:24px;" v-if="itemVisible(item)" ) {{item.prop}} visible-->
              el-form-item(v-bind:ref="item.prop||null" v-bind:label="item.label" v-bind:prop="item.prop" v-bind:key="item.prop")
                el-select(v-if="item.type==='select'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType"
                v-bind:clearable="item.clearable")
                  el-option(v-for="option in item.options" v-bind:key="option.value" v-bind:label="option.label" v-bind:value="option.value")
                kalix-select2(v-else-if="item.type==='select2'" v-model="form[item.prop]" v-bind:optionsUrl="item.optionsUrl" v-bind:optionKey="item.optionValue" v-bind:label="item.optionLabel"
                v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType")
                el-input-number(v-else-if="item.type==='number'" v-model="form[item.prop]" v-bind:class="bindCls(item.cls)" v-bind:data-type="item.dataType")
                kalix-tree2.inline(v-else-if="item.type==='tree'" v-model="form[item.prop]" v-bind:treeDataURL="item.treeDataURL" v-bind:isAll="item.isAll")
                kalix-object-select2(v-else-if="item.type==='object2'" v-model="form[item.prop]" v-bind:objectsUrl="item.objectsUrl" v-bind:label="item.fieldName")
                kalix-date-picker(v-else-if="item.type==='date'" v-model="form[item.prop]")
                kalix-date-picker(v-else-if="item.type==='year'" v-model="form[item.prop]" type="year")
                kalix-datetime-picker(v-else-if="item.type==='datetime'" v-model="form[item.prop]")
                kalix-dict-select(v-else-if="item.type==='dict'" v-bind:appName="item.appName" v-bind:dictType="item.dictType" v-model="form[item.prop]")
                Kalix-map-select(v-else-if="item.type==='map'" v-bind:appName="item.appName" v-bind:prop="item.prop" v-bind:selectUrl="item.selectUrl" v-model="form[item.prop]"
                v-bind:selectedOptions="item.options" v-on:getProp="getProp" v-on:input="getSelectValue" v-bind:stopChange="item.stopChange")
                input(v-else-if="item.type==='inputHidden'" v-model="form[item.prop]" type="hidden")
                el-input(v-else v-model="form[item.prop]")
        el-form-item
          el-button(type="success" v-on:click="onSubmitClick")
            i.iconfont.icon-query
            | 查询
          el-button(type="primary" v-on:click="onResetClick")
            i.iconfont.icon-reset
            | 重置
</template>

<script>
  import {strToUnicode} from '../../common/unicode-convert'
  import {isEmptyObject} from '../../common/util'
  import EventBus from '../../common/eventbus'
  import {ON_SEARCH_BUTTON_CLICK} from './event.toml'

  export default {
    name: 'kalix-search',
    activated() {
      console.log('[kalix] base search ' + '  is activated')
    },
    deactivated() {
      console.log('[kalix] base search ' + '  is deactivated')
    },
    data() {
      return {
        form: {},
        isSearch: false,
        queryStrs: {},
        rules: {
          req: [{required: true, message: '查询条件必填!'}]
        },
        kk: {}
      }
    },
    props: {
      bizKey: {
        type: String,
        default: ''
      },
      searchForm: {
        type: Object
      },
      title: {
        type: String,
        default: ''
      },
      searchFields: { // 搜索查询的字段
        type: Array
      },
      formRules: null
    },
    created() {
      console.group(' ===== searchFields ===== ', this.searchFields)
      if (this.searchFields && Array.isArray(this.searchFields)) {
        this.searchFields.forEach(item => {
          console.log(' ===== item ===== ', item)
          console.log(' ===== item.isVisible ===== ', item.isVisible !== undefined)
          if (item.isVisible !== undefined) {
            this.$set(this.kk, item.prop, {visible: item.isVisible})
          }
        })
      }
      console.groupEnd()
      this._currentForm()
    },
    mounted() {
    },
    methods: {
      itemVisible(item) {
        console.log('prop:' + item.prop)
        let result = this.kk[item.prop] === undefined
        if (!result) {
          result = this.kk[item.prop].visible
        }
        return result
      },
      selectEvent(eventKey, item, value) {
        if (typeof (item.event[eventKey]) === 'function') {
          item.event[eventKey](value, this.kk)
        }
      },
      bindFormDataType(e) {
        this.formDataType[e.prop] = e.dataType || e.type || 'string'
        this.formDataField[e.prop] = e.field || null
      },
      bindCls(label) {
        if (label) {
          return label.length > 0 ? `${this.bizKey}-${label}` : ''
        }
        return ''
      },
      _currentForm() {
        console.log('_currentForm')
        this.isSearchFrom = false
        this.formDataType = {}
        this.formDataField = {}
        if (!isEmptyObject(this.searchForm)) { // 是否传入 searchForm
          this.form = this.searchForm
          this.isSearchFrom = true
        } else {
          this.searchFields.forEach(item => {
            this.bindFormDataType(item)
            if (item.defaultVal) {
              this.$set(this.form, item.prop, item.defaultVal)
            } else {
              this.$set(this.form, item.prop, null)
            }
          })
        }
      },
      // 提交查询
      onSubmitClick() {
        this.$refs.searchForm.validate((valid) => {
          if (valid) {
            console.log('onSubmitClick')
            console.log('this.form', this.form)
            console.log('this.isSearchFrom', this.isSearchFrom)
            let requestDatas = []
            for (let item in this.form) {
              const itemVal = this.form[item]
              if (this.isSearchFrom) { // 如果有 SearchFrom 传入
                let dataType = typeof itemVal
                let field = item
                let docItems = document.getElementsByClassName(`${this.bizKey}-${item}`) // 根据 bizKey 和 v-model名 查找 dom 标签
                console.log('docItems', docItems)
                if (docItems && docItems.length === 1) {
                  //  如果 docItems 存在并且只有一个，获取当前字段的数据类型并赋值给 dataType
                  let docItem = docItems[0]
                  console.log('docItem', docItem)
                  dataType = docItem.getAttribute('data-type')
                  field = docItem.getAttribute('field')
                  console.log('dataType', dataType)
                  console.log('field', field)
                  console.log('itemVal', itemVal)
                  console.log('itemVal.length', itemVal.length)
                  if (field && itemVal.length) {
                    let key = `"${field}"` // 绑定 查询 key
                    let val = `${itemVal}` // 绑定 查询 value
                    switch (dataType) {
                      case 'string':
                        //  如果 dataType 是 String 格式，key 和 val 增加双引号
                        key = `"%${field}%"`
                        if (this.isChinese(itemVal)) {
                          val = `"${strToUnicode(itemVal)}"`
                        } else {
                          val = `"${itemVal}"`
                        }
                        break
                      case 'datetime':
                        //  如果 dataType 是 Datetime 格式，val 增加双引号
                        key = `"${field}"`
                        val = `"${itemVal}"`
                        console.log('如果 dataType 是 Datetime 格式，val 增加双引号')
                        console.log('key', key)
                        console.log('val', val)
                        break
                      case 'orgTree':
                        val = `${itemVal}`
                        break
                    }
                    requestDatas.push(`${key}: ${val}`)
                  }
                  console.log('requestDatas', requestDatas)
                }
              } else {
                if (itemVal !== undefined && itemVal !== null) {
                  let field = item
                  let key = `"${field}"` // 绑定 查询 key
                  let val = `"${itemVal}"` // 绑定 查询 value
                  if (this.formDataField[item]) {
                    key = `"${this.formDataField[item]}"`
                  } else if (this.formDataType[item] === 'string') {
                    key = `"%${field}%"`
                  }
                  switch (this.formDataType[item]) {
                    case 'string':
                      if (this.isChinese(itemVal)) {
                        val = `"${strToUnicode(itemVal)}"`
                      }
                      break
                    case 'number':
                      val = `${itemVal}`
                      break
                  }
                  requestDatas.push(`${key}: ${val}`)
                }
              }
            }
            let searchObj = {}
            if (requestDatas.length > 0) {
              searchObj.jsonStr = `{${requestDatas.join(',')}}`
            }
            this.isSearch = true
            // 兼容多个basetable查询情况
            let searchObjAll = {}
            if (this.bizKey) {
              searchObjAll.searchObj = searchObj
              searchObjAll.bizKey = this.bizKey
            } else {
              searchObjAll = searchObj
            }
            console.log('searchObjAll', searchObjAll)
            // EventBus.$emit(ON_SEARCH_BUTTON_CLICK, searchObj)
            EventBus.$emit(ON_SEARCH_BUTTON_CLICK, searchObjAll)
          } else {
            console.log('ERR')
          }
        })
      },
      // 重置搜索框
      onResetClick() {
        this.$refs.searchForm.resetFields()
        if (this.isSearch) {
          EventBus.$emit(ON_SEARCH_BUTTON_CLICK, {})
          this.isSearch = false
        }
      },
      // 是否是数字
      isNumberData(_data) {
        const regNumber = /^[0-9]+.?[0-9]*$/
        return regNumber.test(_data)
      },
      isChinese(str) {
        let strExp = new RegExp(/^[\u4E00-\u9FA5]+$/)
        if (strExp.test(str)) {
          return true
        }
        return false
      },
      getProp(val) {
        this.$emit('getProp', val)
      },
      getSelectValue(val) {
        this.$emit('selectVal', val)
      }
    },
    components: {},
    computed: {},
    watch: {}
  }
</script>
